package configstc

import (
	"strconv"
	"strings"
)

type CommonExtendParams map[string]string

// ExtendParamByInt 返回extendParam指定k的int类型值
func (op CommonExtendParams) ExtendParamByInt(k string, def ...int) int {
	v := op.ExtendParamValue(k)
	ret, err := strconv.Atoi(v)
	if err != nil {
		if len(def) > 0 {
			return def[0]
		}
		return 0
	}
	return ret
}

// ExtendParamByInt64 返回extendParam指定k的int类型值
func (op CommonExtendParams) ExtendParamByInt64(k string, def ...int64) int64 {
	v := op.ExtendParamValue(k)
	ret, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		if len(def) > 0 {
			return def[0]
		}
		return 0
	}
	return ret
}

// ExtendParamByFloat 返回extendParam指定k的float类型值
func (op CommonExtendParams) ExtendParamByFloat(k string, def ...float64) float64 {
	v := op.ExtendParamValue(k)
	ret, err := strconv.ParseFloat(v, 64)
	if err != nil {
		if len(def) > 0 {
			return def[0]
		}
		return 0
	}
	return ret
}

// ExtendParamByBool 返回extendParam指定k的bool类型值
func (op CommonExtendParams) ExtendParamByBool(k string, def ...bool) bool {
	v := op.ExtendParamValue(k)
	if v == "" {
		if len(def) > 0 {
			return def[0]
		}
		return false
	}

	if v == "true" {
		return true
	}

	if v == "false" {
		return true
	}

	return v != "0"
}

func (op CommonExtendParams) ExtendParamValue(key string, def ...string) string {
	if op == nil {
		return ""
	}
	v := strings.TrimSpace(op[key])
	if v == "" {
		if len(def) > 0 {
			return def[0]
		}
		return ""
	}

	return v
}
